<template>
  <div>
      <!-- 面包屑导航区域 -->
    <nav-bread name1="商品管理" name2="参数列表"></nav-bread>

    <!-- 卡片区域 -->
    <el-card>
        <!-- 警告文案 -->
    <el-alert
    title="注意:只允许为第三级分类设置相关参数"
    type="warning"
    show-icon close-text="了解">
  </el-alert>

   <!-- 选择商品分类区域 -->
   <el-row class="cat_row">
    <el-col>
        <span>选择商品分类：</span>
        <!-- 选择商品分类的级联选择框 -->
        <div class="block">
  <el-cascader
    v-model="cateValue"
    clearable
    :options="cateList"
    @change="cateChange"
    :props="{ expandTrigger: 'hover' ,label:'cat_name',value:'cat_id',children:'children'}"
     ></el-cascader>
    </div>
    </el-col>
   </el-row>
       <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 添加动态参数面板 -->
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" :disabled="isDisabledCate"
        @click="addDialogVisible=true">添加参数</el-button>
        <!-- 动态参数表格 -->
        <el-table :data="manyTableData" border stripe v-if="cateValue.length==3">
            <!-- 展开行 -->
       <el-table-column type="expand">
         <template slot-scope="scope" >
             <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable 
             @close="handleClose(i,scope.row)">
               {{item}}
             </el-tag>
                          <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
         </template>
       </el-table-column>
       <!-- 索引列 -->
       <el-table-column type="index"></el-table-column>
       <el-table-column label="参数名称" prop="attr_name"></el-table-column>
       <el-table-column label="操作" >
        <template slot-scope="scope">
           <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
           <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeCate(scope.row.attr_id)">删除</el-button>
        </template>
       </el-table-column>
        </el-table>
    </el-tab-pane>

          <!-- 添加静态属性面板 -->
    <el-tab-pane label="静态属性" name="only" v-if="cateValue.length==3"
    >
        
        <el-button type="primary" :disabled="isDisabledCate" @click="addDialogVisible=true">添加属性</el-button> 
         <!-- 动态参数表格 -->
        <el-table :data="onlyTableData" border stripe v-if="cateValue.length==3">
            <!-- 展开行 -->
       <el-table-column type="expand">
         <!-- 循环渲染tag标签 -->
         <template slot-scope="scope" >
             <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
               {{item}}
             </el-tag>
                          <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
         </template>
       </el-table-column>
       <!-- 索引列 -->
       <el-table-column type="index"></el-table-column>
       <el-table-column label="参数名称" prop="attr_name"></el-table-column>
       <el-table-column label="操作" >
        <template slot-scope="scope">
           <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
           <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeCate(scope.row.attr_id)">删除</el-button>
        </template>
       </el-table-column>
        </el-table>

    </el-tab-pane>
  </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
  :title="isMany"
  :visible.sync="addDialogVisible"
  width="50%"
  @close="addClose">
<el-form :model="addForm" :rules="rules" ref="addRuleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="参数名称" prop="attr_name">
    <el-input v-model="addForm.attr_name"></el-input>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
</el-dialog>
   
   <!-- 修改参数对话框 -->
       <el-dialog
  :title="isMany"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editClose">
<el-form :model="editForm" :rules="editRules" ref="editRuleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="参数名称" prop="attr_name">
    <el-input v-model="editForm.attr_name"></el-input>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
   data() {
       return {
        //    初始化数据列表数据
           cateList:[],
        //    级联选择器的值
           cateValue:[],
        //    tab页签绑定的值
           activeName:'many',
        //    获取到的动态参数
           manyTableData:[],
        //    获取到的静态属性
           onlyTableData:[],
        //    添加动态/静态对话框的显示与隐藏
           addDialogVisible:false,
        //    添加的属性
           addForm:{
               attr_name:'',
           },
        //    添加表单的验证规则
            rules:{
                attr_name:[{ required: true, message: '请输入参数名称', trigger: 'blur' },
                { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }]
            },
            // 修改对话框的显示与隐藏
           editDialogVisible:false,
        //    修改表单的数据对象
            editForm:{
                attr_name:''
            },
            // 修改表单的验证规则对象
            editRules:{attr_name:[{ required: true, message: '请输入参数名称', trigger: 'blur' },
                { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }]},
                // 控制按钮与文本框的显示和隐藏
                inputVisible:false,
                // 文本框中的内容
                inputValue:'',
       }
   },
        created(){
         this.getCateList()
     },
     computed:{
        //  动态计算添加按钮的能否使用
         isDisabledCate(){
             return this.cateValue.length!==3;
         },
        //  动态计算对话框的标题文本
         isMany(){
          if(this.activeName==='many'){
              return '添加动态参数';
          }else return '添加静态属性';
         },
     },
    methods:{
        //  初始化，获取商品分类的数据列表
   async getCateList(){
        const { data } = await this.$http.get("categories");
      if (data.meta.status !== 200)
        return this.$message.error("获取商品数据列表失败");
      this.cateList = data.data;
    },
    // 点击页签所绑定的值
    handleClick(){
    this.cateChange();
    },
    // 选择的次联选择器改变时发送请求
   async cateChange(){
       if(this.cateValue.length!==3)return;
       const {data,}=await this.$http.get(`categories/${this.cateValue[2]}/attributes`,{params:
        {sel:this.activeName}});
        if(data.meta.status!==200)return this.$message.error('获取参数失败');
        console.log(data.data);
           data.data.forEach(item => {
             item.attr_vals=item.attr_vals?item.attr_vals.split(','):[]
            //  给获取到的每一项都添加控制input输入的属性
          item.attr_vals=item.attr_vals.filter((value)=>{
                return value&&value.trim();

            });
            console.log(item.attr_vals);
            item.inputVisible=false;
            item.inputValue='';
           });
         if(this.activeName=='many'){
             return this.manyTableData=data.data;
         }else this.onlyTableData=data.data;
         console.log(this.onlyTableData);
    },
    // 添加参数对话框关闭事件
    addClose(){
        this.$refs.addRuleForm.resetFields()
    },
    // 添加参数
    addParams(){
     this.$refs.addRuleForm.validate(async valid=>{
         if(!valid)return this.$message.error('请填写参数');
         let id=this.cateValue[2];
        const {data,}=await this.$http.post(`categories/${id}/attributes`,{
          attr_name:this.addForm.attr_name,attr_sel:this.activeName
         });
         if(data.meta.status!==201)return this.$message.error('添加失败');
         this.$message.success('添加成功');
         this.cateChange();
         this.addDialogVisible = false;
     });
    },
    // 编辑对话框关闭事件
    editClose(){
    this.$refs.editRuleForm.resetFields()
    },
        // 编辑对话框的显示
   async showEditDialog(id){
        let cateId=this.cateValue[2];
      const {data,}=await this.$http.get(`categories/${cateId}/attributes/${id}`,{
            attr_sel:this.activeName,
        })
        if(data.meta.status!==200)return this.$message.error('获取参数信息失败');
        this.editForm=data.data;
         this.editDialogVisible=true;
    },
    // 编辑参数
     editParams(){
       this.$refs.editRuleForm.validate(async valid=>{
         if(!valid)return this.$message.error('请填写参数');
         let id=this.cateValue[2];
        const {data,}=await this.$http.put(`categories/${id}/attributes/${this.editForm.attr_id}`,{
          attr_name:this.editForm.attr_name,attr_sel:this.activeName,attr_vals:this.editForm.attr_vals
         });
         if(data.meta.status!==200)return this.$message.error('更新失败');
         this.$message.success('更新成功');
         this.cateChange();
         this.editDialogVisible = false;
     });
     },
    //  删除参数
    async removeCate(id){
             let cateId=this.cateValue[2];    
     const confirmResult=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        ;
        // 用户确认删除
        // 用户确认删除，返回值是confirm
        // 取消返回值是cancel
        if(confirmResult!=='confirm'){
          return this.$message.info('已取消删除')
        }
        // 用户确认删除，发送请求删除该数据
        const {data}=await this.$http.delete(`categories/${cateId}/attributes/${id}`)
        if(data.meta.status!==200) return this.$message.error(data.meta.msg);
         this.$message.success('删除成功');
         this.cateChange();
     },
    //  文本框失去焦点，或者回车都会触发的事件
    handleInputConfirm(row){
      // 判断是否是没输入(预校验)
      if(row.inputValue.trim().length===0){
        row.inputValue='';
        row.inputVisible=false;
        this.$message.error('请不要输入空值');
        return
      }
      this.savaValue(row);
    },
    // 添加或删除参数
   async savaValue(row){
      row.attr_vals.push(row.inputValue.trim());
      let id=this.cateValue[2];
    const{data,}= await this.$http.put(`categories/${id}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:row.attr_vals.join(',')
      });
      if(data.meta.status!==200) return this.$message.error(data.meta.msg);
         this.$message.success('操作成功');
            row.inputValue='';
      row.inputVisible=false;
    },
    // 点击按钮，展示文本框
    showInput(row){
      row.inputVisible=true;
      // 点击按钮自动展示文本框
      this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 关闭tag标签
    handleClose(i,row){
      row.attr_vals.splice(i,1);
      row.attr_vals.filter(item=>{
        return item!=='';
      })
      this.savaValue(row);
      this.cateChange();
    }
    }
}
</script>

<style lang="less" scoped>
.cat_row{
 margin: 15px auto;
}
.el-tag{
  margin: 5px 15px;
}
.el-input{
  width: 150px;
}
</style>

